package org.mock.utils;

import org.docx4j.Docx4J;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WordToPdfConverter {

    public static void convert(String wordPath, String pdfPath) throws Exception {
        ClassPathResource resource = new ClassPathResource(wordPath);
        try (InputStream is = resource.getInputStream()) {
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);

            // 设置字体映射
            IdentityPlusMapper fontMapper = new IdentityPlusMapper();
            fontMapper.put("SimSun", PhysicalFonts.get("simsun.ttf")); // 直接指定字体文件
            wordMLPackage.setFontMapper(fontMapper);

            // 导出为 PDF
            try (OutputStream os = Files.newOutputStream(Paths.get(pdfPath))) {
                Docx4J.toPDF(wordMLPackage, os);
            }
        }
    }
}